<?php

class SJB_ShoppingCart
{
	public static function addToShoppingCart($productInfo, $userSID)
	{
		return SJB_DB::query("INSERT INTO `shopping_cart` (`user_sid`, `product_info`) VALUES (?n, ?s)", $userSID, serialize($productInfo));
	}
	
	public static function getAllProductsByUserSID($userSID)
	{
		return  SJB_DB::query("SELECT * FROM `shopping_cart` WHERE `user_sid` = ?n ORDER BY `sid` DESC", $userSID);
	}
	
	public static function deleteItemFromCartBySID($sid, $userSID)
	{
		return  SJB_DB::query("DELETE FROM `shopping_cart` WHERE `user_sid` = ?n AND `sid` = ?n", $userSID, $sid);
	}
	
	public static function updateItemBySID($sid, $productInfo)
	{
		return SJB_DB::query("UPDATE `shopping_cart` SET `product_info` = ?s WHERE `sid` = ?n ", serialize($productInfo), $sid);
	}
	
	public static function deleteItemsFromCartByUserSID($userSID)
	{
		return  SJB_DB::query("DELETE FROM `shopping_cart` WHERE `user_sid` = ?n", $userSID);
	}

	public static function getProductsInfoAlreadyCheckedByUserSID($userSID)
	{
		$serializedProductsInfo = SJB_DB::query('SELECT `product_info` FROM `shopping_cart` WHERE `user_sid` = ?n ORDER BY `sid` DESC', $userSID);
		$alreadyCheckedProducts = array();
		if (is_array($serializedProductsInfo)) {
			foreach ($serializedProductsInfo as $serializedInfo) {
				array_push($alreadyCheckedProducts, unserialize($serializedInfo['product_info']));
			}
		}
		return $alreadyCheckedProducts;
	}

	public static function getProductsInfoAlreadyCheckedForGuest()
	{
		$serializedProductsInfo = SJB_Session::getValue('products');
		$alreadyCheckedProducts = array();
		if (is_array($serializedProductsInfo)) {
			foreach ($serializedProductsInfo as $serializedInfo) {
				array_push($alreadyCheckedProducts, unserialize($serializedInfo['product_info']));
			}
		}
		return $alreadyCheckedProducts;
	}
	
	public static function deleteItemsFromCartByProductSID($productSID)
	{
		$productSID = '"sid";s:'.strlen($productSID).':"'.$productSID.'"';
		return  SJB_DB::query("DELETE FROM `shopping_cart` WHERE `product_info` LIKE '%{$productSID}%'");
	}
}